package com.starpl.mobile.android.monthunsae.november.activity;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.starpl.mobile.android.monthunsae.november.R;
import com.starpl.mobile.android.monthunsae.november.domain.UserInfo;
import com.starpl.mobile.android.platform.command.StarplCommand;
import com.starpl.mobile.android.platform.common.CameraUtil;
import com.starpl.mobile.android.platform.common.KeywordUtil;
import com.starpl.mobile.android.platform.common.base.BaseActivity;
import com.starpl.mobile.android.platform.common.base.BaseApplication;
import com.starpl.mobile.android.platform.common.image.ImageDownloader;
import com.starpl.mobile.android.platform.common.network.HttpHandler;

/**
 * 글을 작성하는 클래스
 * 
 * @author 박우람
 * @since 2011.03.19
 */
public class WriteActivity extends BaseActivity implements OnClickListener
{
	public static final int TYPE_POST = 0;
	public static final int TYPE_REPLY = 1;
	
	private static final int IMAGE_RESIZE_LIMIT = 400;
	
	private ImageButton mIbComplete; 
	private TextView mTvCommunity;
	private EditText mEtWriteContent;
	private TextView mTvCharacterLimit;
	private ImageView mIvUploadedImage;
	private ImageButton mIbPictureAppend;
	private ImageButton mIbPictureDelete;
	private CameraUtil mCamera;
	
	private int mKeywordIdx;
	private int mPostIdx;
	private int mWriteType;
	private String mRcvStarName;
	
	private String mPostImgPath = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.write_activity);

		// 필요한 데이터 가져옴
		Bundle extras = getIntent().getExtras();
		
		mKeywordIdx = extras.getInt("keywordIdx");
		mPostIdx = extras.getInt("postIdx", 0);		
		mWriteType = extras.getInt("type");
		
		// 타이틀
		TextView tvTitle = (TextView) findViewById(R.id.write_activity_tv_title);
		
		// 글종류
		TextView tvTitleMid = (TextView) findViewById(R.id.write_activity_tv_mid_title);
		
		// 완료버튼
		mIbComplete = (ImageButton) findViewById(R.id.write_activity_ib_complete);
		mIbComplete.setOnClickListener(this);
		
		// 관심사
		mTvCommunity = (TextView) findViewById(R.id.write_activity_tv_favorite_keyword);
		
		switch(mWriteType)
		{
		case TYPE_REPLY:
			tvTitle.setText("댓글쓰기");
			tvTitleMid.setText("댓글쓰기 to.");
			mRcvStarName = extras.getString("rcvStarName");
			mTvCommunity.setText(mRcvStarName);
			break;
			
		case TYPE_POST:
		default:
			tvTitle.setText("글쓰기");
			tvTitleMid.setText("글쓰기");
			mTvCommunity.setText("(" + KeywordUtil.getInstance().getKeywordName(mKeywordIdx) + ")");
			break;
		}
		
		// 에딧텍스트, 사용자입력 글
		mEtWriteContent = (EditText) findViewById(R.id.write_activity_et_comment);
		mEtWriteContent.addTextChangedListener(watcher);
		
		// 글자수 제한
		mTvCharacterLimit = (TextView) findViewById(R.id.write_activity_tv_comment_limit);
		
		mIvUploadedImage = (ImageView) findViewById(R.id.write_activity_iv_uploadedImage);
		
		// 사진첨부/삭제
		mIbPictureAppend = (ImageButton)findViewById(R.id.write_activity_ib_picture_append);
		mIbPictureDelete = (ImageButton)findViewById(R.id.write_activity_ib_picture_delete);
		
		mIbPictureAppend.setOnClickListener(this);
		mIbPictureDelete.setOnClickListener(this);
	}

	@Override
	public void onClick(View v)
	{
		UserInfo userInfo = (UserInfo)BaseApplication.getGlobalPersistent("userInfo");
		switch (v.getId())
		{
			// 글쓰기 완료 버튼
			case R.id.write_activity_ib_complete:
				HttpHandler httpHandler = new HttpHandler(this)
				{
					@Override
					public void didSucceed(Object result)
					{
						setResult(RESULT_OK);
						WriteActivity.this.finish();
					}
				};
				
				String userId = userInfo.getUserId();
				String comment = mEtWriteContent.getText().toString();
				
				// 작성된 글이 없을 경우
				if(comment.length() == 0)
				{
					alert("글을 작성해 주십시오");
					return;
				}
				
				switch(mWriteType)
				{
				// 댓글쓰기
				case TYPE_REPLY:
					StarplCommand.writeReply(httpHandler, userId, mPostIdx, comment, mKeywordIdx, mPostImgPath);
					return;

				// 일반 글쓰기
				default:
					StarplCommand.writePost(httpHandler, userId, comment, mKeywordIdx, mPostImgPath);
					return;
				}
				
			// 사진첨부
			case R.id.write_activity_ib_picture_append:
				mCamera = new CameraUtil(this);
				mCamera.openCameraOrAlbum(userInfo.getUserIdx(), IMAGE_RESIZE_LIMIT);
				break;
			
			// 사진 삭제
			case R.id.write_activity_ib_picture_delete:
				mIbPictureAppend.setVisibility(ImageButton.VISIBLE);
				mIbPictureDelete.setVisibility(ImageButton.GONE);
				mIvUploadedImage.setVisibility(ImageView.GONE);
				mPostImgPath = null;
				break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if(resultCode == RESULT_OK)
		{
				HttpHandler uploadHandler = new HttpHandler(this)
				{
					@Override
					public void didSucceed(Object result)
					{
						try
						{
							JSONObject object = new JSONObject(result.toString());
							String hostName = object.getString("hostname");
							String imagePath = object.getString("original");
							mPostImgPath = "http://" + hostName + imagePath;
							
							mIvUploadedImage.setVisibility(ImageView.VISIBLE);
							mIvUploadedImage.setImageBitmap(null);
							ImageDownloader.download(mPostImgPath, mIvUploadedImage);
						}
						catch(JSONException e)
						{
							LOG.e(e.getMessage());
						}
					}
				};
				
				mCamera.process(requestCode, data, uploadHandler);
			}
			
			// 버튼 교체
			mIbPictureAppend.setVisibility(ImageButton.GONE);
			mIbPictureDelete.setVisibility(ImageButton.VISIBLE);
	}

	private TextWatcher watcher = new TextWatcher()
	{
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count)
		{
			String text = s.toString();
			int limitLength = 300 - text.length();
			mTvCharacterLimit.setText(Integer.toString(limitLength));
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) 
		{
		}
		
		@Override
		public void afterTextChanged(Editable s){}
	};
}
